//
//  SCPhotoTools.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/1.
//

#import "SCPhotoTools.h"

@implementation SCPhotoTools

+ (UIImage *)imageLineWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    [color setFill];
    UIRectFill(rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}

/**
 相册名称转换
 */
+ (NSString *)transFormPhotoTitle:(NSString *)englishName {
    NSString *photoName;
    if ([englishName isEqualToString:@"Bursts"]) {
        photoName = @"连拍快照";
    }else if([englishName isEqualToString:@"Recently Added"]){
        photoName = @"最近添加";
    }else if([englishName isEqualToString:@"Screenshots"]){
        photoName = @"屏幕快照";
    }else if([englishName isEqualToString:@"Camera Roll"]){
        photoName = @"相机胶卷";
    }else if([englishName isEqualToString:@"Selfies"]){
        photoName = @"自拍";
    }else if([englishName isEqualToString:@"My Photo Stream"]){
        photoName = @"我的照片流";
    }else if([englishName isEqualToString:@"Videos"]){
        photoName = @"视频";
    }else if([englishName isEqualToString:@"All Photos"]){
        photoName = @"所有照片";
    }else if([englishName isEqualToString:@"Slo-mo"]){
        photoName = @"慢动作";
    }else if([englishName isEqualToString:@"Recently Deleted"]){
        photoName = @"最近删除";
    }else if([englishName isEqualToString:@"Favorites"]){
        photoName = @"个人收藏";
    }else if([englishName isEqualToString:@"Panoramas"]){
        photoName = @"全景照片";
    }else {
        photoName = englishName;
    }
    return photoName;
}

+ (NSString *)transFromDateTime:(NSDate *)date {
    
    if ([date isToday]) {
        return  @"今天";
        
    } else if ([date isYesterday]) {
        return @"昨天";
        
    } else if ([date isSameWeek]) {
        return [date getNowWeekday];
        
    } else if ([date isThisYear]) {
        return [NSString stringWithFormat:@"%@ %@",[date dateStringWithFormat:@"MM月dd日"],[date getNowWeekday]];
        
    } else {
        return [date dateStringWithFormat:@"yyyy年MM月dd日"];
    }
}

+ (NSString *)transFromYMDTime:(NSDate *)date {
    return [date dateStringWithFormat:@"yyyy年MM月dd日"];
}

+ (NSString *)transFromMHTime:(NSDate *)date {
    return [date dateStringWithFormat:@"HH:mm"];
}

/**
 *  是否为同一天
 */
+ (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}


// 是否是刘海屏手机
+ (BOOL)deviceIsPhoneX {
    BOOL iPhoneX = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {//判断是否是手机
        return iPhoneX;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            iPhoneX = YES;
            
        }
    }
    return iPhoneX;
}

+(void)getPhotoForPHAsset:(PHAsset *)asset size:(CGSize)size completion:(void (^)(UIImage * _Nonnull, PHAsset * _Nonnull))completion {
    
    if (asset==nil) {
        NSLog(@"出现错误，asset=nil");
        return;
    }
    
    PHImageRequestOptions * option = [[PHImageRequestOptions alloc] init];
    //图片质量设置
    option.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    option.resizeMode = PHImageRequestOptionsResizeModeFast;
    //当图片是iCloud时是否通过网络获取
    option.networkAccessAllowed = NO;
    //是否为同步
    option.synchronous = NO;
    
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        if ([[info objectForKey:PHImageResultIsInCloudKey] boolValue]) {
            NSLog(@"icloud上的资源!!!");
        }
        BOOL downloadFinined = (![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey]);
        if (downloadFinined && result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result,asset);
            });
        } else {
            result = [UIImage sc_bundleImageNamed:@"LGQ-placeholderImg"];
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result,asset);
            });
        }
    }];
}

+ (BOOL)requestAuthorization:(UIViewController*)vc type:(NSString*)type {
    
    if ([type isEqualToString:@"photo"]) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status != PHAuthorizationStatusAuthorized) {
             //判断没有赋予权限时的显示
            NSString *app_Name = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
            NSString *title = [NSString stringWithFormat:@"请您先去设置允许%@访问您的相册 设置>隐私>照片",app_Name];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [vc dismissViewControllerAnimated:YES completion:nil];
            }];
            [alert addAction:action];

            [vc presentViewController:alert animated:YES completion:nil];
            
            return NO;
        }

    } else if ([type isEqualToString:@"camera"]) {

        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized) {
            NSString *app_Name = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
            NSString *title = [NSString stringWithFormat:@"请您先去设置允许%@使用您的相机 设置>隐私>相机",app_Name];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [vc dismissViewControllerAnimated:YES completion:nil];
            }];
            [alert addAction:action];
            [vc presentViewController:alert animated:YES completion:nil];
            
            return NO;
        }
    }
    
    return YES;
}

@end
